<script setup lang="ts">
// 路由
import router from "@/router";
// 组件
import LangSelect from "@/components/LangSelect/index.vue";
import SvgIcon from "@/components/SvgIcon/index.vue";
// 状态管理依赖
import { useUserStore } from "@/store/modules/user";
// API依赖
import { LocationQuery, LocationQueryValue, useRoute } from "vue-router";
import { LoginData, phoneLoginData, phoneLoginDatato } from "@/api/auth/types";
import { getCaptchaApi, getPhoneCaptchaApi } from "@/api/auth";
// 规则校验
import { FormRules } from "element-plus";

const userStore = useUserStore();
const route = useRoute();
// 表单类型，login 登录，sms 验证码登录
let formType = ref("login");
// 验证码图片Base64字符串
const captchaBase64 = ref();
// 账号登录按钮加载状态
const loading = ref(false);
// 获取表单
const loginFormRef = ref(ElForm);
// 账号密码登录
const loginData = ref<LoginData>({});
// 校验规则
const loginRules = ref<FormRules>({
  // 用户名
  username: [{ required: true, trigger: "blur", message: "请填写手机账号" }],
  // 密码
  password: [{ required: true, trigger: "blur", validator: passwordValidator }],
  // 验证码
  verifyCode: [
    { required: true, trigger: "blur", message: "请填写数字验证码" },
  ],
});
// 获取表单
const SmsRef = ref(ElForm);
// 手机号验证码按钮加载状态
const smsloading = ref(false);
// 手机号验证码请求参数
let SmsLogin = ref<phoneLoginData>({
  phone: "",
  smsCode: "",
});
// 验证码判断请求参数
const captchaLogin = ref<phoneLoginDatato>({
  phone: "",
});
// 手机号验证码校验规则
const SmsRules = ref<FormRules>({
  // 手机号
  phone: [{ required: true, trigger: "blur", validator: phoneValidator }],
});
// 获取手机验证码 图片倒计时
const mobileCodeTimer = ref(0);

// passwordValidator(密码校验器)
function passwordValidator(_rule: any, value: any, callback: any) {
  if (!value) {
    callback(new Error("请输入密码"));
  }

  if (value.length < 6 || value.length > 18) {
    callback(new Error("密码长度6-18位"));
  } else {
    callback();
  }
}
// 获取数字验证码函数
function getCaptcha() {
  getCaptchaApi().then(({ data }) => {
    const { verifyCodeBase64, verifyCodeKey } = data; // 解构出需要的数据
    captchaLogin.value.verifyCodeKey = verifyCodeKey; // 将值交给手机号验证码登录
    loginData.value.verifyCodeKey = verifyCodeKey; // 将值交给账号密码登录
    captchaBase64.value = verifyCodeBase64;
  });
}
// 账号密码登录函数
function handleLogin() {
  loginFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      userStore
        .login(loginData.value)
        .then(() => {
          const query: LocationQuery = route.query;

          const redirect =
            (query.redirect as LocationQueryValue) ?? "/me/personal";

          const otherQueryParams = Object.keys(query).reduce(
            (acc: any, cur: string) => {
              if (cur !== "redirect") {
                acc[cur] = query[cur];
              }
              return acc;
            },
            {}
          );
          ElMessage.success("登录成功,请稍后");
          router.push({ path: redirect, query: otherQueryParams });
        })
        .catch(() => {
          // 验证失败，重新生成验证码
          getCaptcha();
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}
// 封装手机号验证规则
function isvalidPhone(phone: string) {
  const reg = /^1([38][0-9]|4[014-9]|[59][0-35-9]|6[2567]|7[0-8])\d{8}$/;
  return reg.test(phone);
}
// 手机号校验器 phoneValidator
function phoneValidator(_rule: any, value: string, callback: any) {
  if (!value) {
    callback(new Error("请填写电话号码"));
  } else if (!isvalidPhone(value)) {
    //判断用户输入的值是否符合规则
    callback(new Error("请填写正确的11位手机号码"));
  } else {
    callback();
  }
}
//获取手机验证码接口函数
function getphoneCaptcha(data: phoneLoginDatato) {
  getPhoneCaptchaApi(data)
    .then((response) => {
      // 设置倒计时
      mobileCodeTimer.value = 60;
      let msgTimer = setInterval(() => {
        mobileCodeTimer.value = mobileCodeTimer.value - 1;
        if (mobileCodeTimer.value <= 0) {
          clearInterval(msgTimer);
        }
      }, 1000);
    })
    .catch(() => {
      // 重新获取验证码
      getCaptcha();
    });
}
// 校验规则  + 只校验手机号
const getSmsCode = () => {
  // 这里只进行手机号规则验证 验证码的对错交给后端判断
  SmsRef.value.validateField(["phone"], (valid: boolean) => {
    if (valid) {
      captchaLogin.value.phone = SmsLogin.value.phone; // 传参
      getphoneCaptcha(captchaLogin.value);
    }
  });
};
// 手机号验证码登录
function handlesms() {
  SmsRef.value.validate((valid: any) => {
    if (valid) {
      smsloading.value = true;
      userStore
        .phonelogin(SmsLogin.value)
        .then(() => {
          const query: LocationQuery = route.query;

          const redirect =
            (query.redirect as LocationQueryValue) ?? "/me/personal";

          const otherQueryParams = Object.keys(query).reduce(
            (acc: any, cur: string) => {
              if (cur !== "redirect") {
                acc[cur] = query[cur];
              }
              return acc;
            },
            {}
          );
          ElMessage.success("登录成功,请稍后");
          router.push({ path: redirect, query: otherQueryParams });
        })
        .catch(() => {
          // 验证失败，重新生成验证码
          getCaptcha();
        })
        .finally(() => {
          smsloading.value = false;
        });
    }
  });
}

// 点击账号密码登录
function accountlogin() {
  // 将展板交给账号密码登录
  formType.value = "login";
  // 点击刷新验证码
  getCaptcha();
}
// 点击手机登录
function SmsLoginbtn() {
  // 将展板交给短信登录
  formType.value = "sms";
  // 点击刷新验证码
  getCaptcha();
}
// 点击注册
function register() {
  router.push("/register");
}
// 模拟忘记密码
function Forgot() {
  router.push("/forget");
}
// 模拟微信扫码登录
function wxlogin() {
  ElMessage.warning("功能待开发");
  // router.push("/wxlogin");
}
// 开始就获取验证码
onMounted(() => {
  getCaptcha(); // 获取验证码
});
</script>

<template>
  <div class="login-bg">
    <div id="login-box">
      <!-- 右主 -->
      <div class="login-banner"></div>
      <!-- 账号密码登录 -->
      <el-form
        v-show="formType === 'login'"
        ref="loginFormRef"
        class="login-form"
        :model="loginData"
        :rules="loginRules"
      >
        <div class="title-container">
          <h3 class="title">{{ $t("login.title") }}</h3>
          <div class="zn">
            <span>
              <!--语言选择-->
              <el-tooltip content="语言切换" placement="top">
                <lang-select
                  class="setting-item"
                  style="font-size: 22px; cursor: pointer"
                />
              </el-tooltip>
            </span>
          </div>
          <div class="sub-link zx" style="margin-top: 14px">
            <span class="text">{{ $t("login.enrollacc") }}</span>
            <el-link v-throttle="register" type="primary" :underline="false">
              {{ $t("login.enroll") }}
            </el-link>
          </div>
        </div>
        <div>
          <el-form-item prop="username">
            <el-input
              v-model="loginData.username"
              type="text"
              :placeholder="$t('login.account')"
              clear
            >
              <template #prefix>
                <svg-icon icon-class="syse_user" />
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="loginData.password"
              type="password"
              :placeholder="$t('login.password')"
              show-password
              clear
            >
              <template #prefix>
                <svg-icon icon-class="password" />
              </template>
            </el-input>
          </el-form-item>

          <!-- 验证码 -->
          <el-form-item prop="verifyCode">
            <el-input
              v-model="loginData.verifyCode"
              auto-complete="off"
              :placeholder="$t('login.verifyCode')"
              class="w-[60%]"
              @keyup.enter="handleLogin"
            >
              <template #prefix>
                <svg-icon icon-class="verify_code" />
              </template>
            </el-input>

            <div class="captcha">
              <img v-throttle="getCaptcha" :src="captchaBase64" />
            </div>
          </el-form-item>
        </div>

        <div class="flex-bar">
          <el-link v-throttle="SmsLoginbtn" type="primary" :underline="false">
            {{ $t("login.sms") }}
          </el-link>
        </div>

        <el-button
          v-throttle="handleLogin"
          type="primary"
          size="large"
          style="width: 100%"
          :loading="loading"
        >
          {{ $t("login.login") }}
        </el-button>

        <div class="sub-link">
          <span class="text">{{ $t("login.fogotacc") }}</span>
          <el-link v-throttle="Forgot" type="primary" :underline="false">
            {{ $t("login.fogot") }}
          </el-link>
        </div>

        <div style="margin-top: 10px; margin-bottom: -10px; text-align: center">
          <el-divider style="opacity: 0.8">{{ $t("login.wx") }}</el-divider>
          <img
            v-throttle="wxlogin"
            style="cursor: pointer"
            src="@/assets/login/wx_logo.png"
            alt=""
            class="wxtb"
          />
        </div>
      </el-form>
      <!-- 短信验证登录 -->
      <el-form
        v-show="formType === 'sms'"
        ref="SmsRef"
        class="login-form"
        :model="SmsLogin"
        :rules="SmsRules"
        auto-complete="on"
      >
        <div class="title-container">
          <h3 class="title">
            {{ $t("smslogin.title") }}
          </h3>
          <div class="zn">
            <span>
              <!--语言选择-->
              <el-tooltip content="语言切换" placement="top">
                <lang-select
                  class="setting-item"
                  style="font-size: 22px; cursor: pointer"
                />
              </el-tooltip>
            </span>
          </div>
        </div>
        <div>
          <!-- 手机号 -->
          <el-form-item prop="phone">
            <el-input
              v-model="SmsLogin.phone"
              :placeholder="$t('smslogin.phone')"
              tabindex="1"
              autocomplete="on"
            >
              <template #prefix>
                <svg-icon icon-class="phone" />
              </template>
            </el-input>
          </el-form-item>
          <!-- 数字验证码 -->
          <el-form-item>
            <el-input
              v-model="captchaLogin.verifyCode"
              auto-complete="off"
              :placeholder="$t('smslogin.verifyCode')"
              class="w-[60%]"
            >
              <template #prefix>
                <svg-icon icon-class="verify_code" />
              </template>
            </el-input>
            <div class="captcha">
              <img v-throttle="getCaptcha" :src="captchaBase64" />
            </div>
          </el-form-item>
          <!-- 短信验证码 -->
          <el-form-item>
            <el-input
              v-model="SmsLogin.smsCode"
              :placeholder="$t('smslogin.captcha')"
              @keyup.enter="handleLogin"
            >
              <template #prefix>
                <svg-icon icon-class="verify_code" />
              </template>

              <template #append>
                <span
                  v-if="mobileCodeTimer <= 0"
                  v-throttle="getSmsCode"
                  class="getMobileCode"
                  style="cursor: pointer"
                >
                  {{ $t("smslogin.fscaptcha") }}
                </span>
                <span
                  v-if="mobileCodeTimer > 0"
                  class="getMobileCode"
                  style="cursor: pointer"
                >
                  {{ mobileCodeTimer }}秒后可重新获取
                </span>
              </template>
            </el-input>
          </el-form-item>
        </div>
        <el-button
          v-throttle="handlesms"
          :loading="smsloading"
          type="primary"
          size="large"
          style="width: 100%; margin-top: 20px"
        >
          {{ $t("smslogin.login") }}
        </el-button>
        <div class="sub-link">
          <el-link v-throttle="accountlogin" type="primary" :underline="false">
            {{ $t("smslogin.account") }}
          </el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
// span no copy
span {
  user-select: none;
}

.login-bg {
  width: 100%;
  height: 100%;
  background: url("@/assets/login/home.jpg") no-repeat;
  background-size: 100% 100%;
}

#login-box {
  position: absolute;
  top: 50%;
  left: 50%;
  display: flex;
  height: 580px;
  background-color: var(--el-bg-color);
  border-radius: 10px;
  box-shadow: var(--el-box-shadow);
  transform: translateX(-50%) translateY(-50%);

  .login-banner {
    position: relative;
    width: 500px;
    margin-top: 55px;
    background: url("@/assets/login/bg_login3.png") no-repeat;
    background-size: 100%;
  }

  .captcha {
    position: absolute;
    top: 0;
    right: 0;

    img {
      width: 100px;
      height: 48px;
      cursor: pointer;
      border: 0.5px solid #dcdcdc;
    }
  }

  .login-form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 500px;
    min-height: 500px;
    padding: 50px;
    overflow: hidden;

    .title-container {
      position: relative;

      .title {
        margin: 0 auto 30px;
        font-size: 1.3em;
        font-weight: bold;
        color: var(--el-text-color-primary);
      }

      .zn {
        position: absolute;
        top: 0;
        right: 0;
      }

      .zx {
        position: absolute;
        top: 15px;
        right: 0;
      }
    }
  }

  .el-form-item {
    margin-bottom: 24px;

    :deep(.el-input) {
      width: 100%;
      height: 48px;
      line-height: inherit;

      input {
        height: 48px;
      }

      .el-input__prefix,
      .el-input__suffix {
        display: flex;
        align-items: center;
      }

      .el-input__prefix {
        left: 10px;
      }

      .el-input__suffix {
        right: 10px;
      }
    }
  }

  .flex-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
  }

  .sub-link {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 20px;
    font-size: 14px;
    color: var(--el-text-color-secondary);

    .text {
      margin-right: 10px;
      opacity: 0.8;
    }
  }
}

.copyright {
  position: absolute;
  bottom: 30px;
  width: 100%;
  margin: 0;
}

.wxtb {
  width: 44px;
  height: 44px;
  margin-top: 15px;
}
</style>
